<template>
  <picker
    mode="multiSelector"
    @change="bindPickerChange"
    @columnchange="columnchange"
    :value="data.index"
    :range="data.array"
    range-key="label">
    <slot></slot>
  </picker>
</template> 

<script lang="ts" setup>
import { reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// import CHINA_CITY from './city.json';
import { queryRegionTwoTree } from '@/service/apis/mine';
const emit = defineEmits(['getRegion']);
interface Props {
  defaultRegion: any;
}
const prop = withDefaults(defineProps<Props>(), {
  defaultRegion: '',
});

const data = reactive({
  defaultRegion: '',
  cityData: [] as any,
  index: [0, 0],
  array: [[], []],
  childArr: [] as any, // 二级分类数据源
  label: '',
});

queryRegionTwoTree({})
  .then((res: any) => {
    console.log('res==queryRegionTwoTree====', res);
    if (res) {
      data.cityData = res;
      getCate();
    }
  })
  .catch(() => {});

// 任务分类
const getCate = () => {
  // 一级分类的数据源
  data.array[0] = data.cityData;
  // 将数据源中的二级分类 push 进 childArr，作为二级分类的数据源
  data.childArr = data.cityData.map((item: { childs: any }) => item.children);
  // console.log('data.childArr =====', data.childArr);

  // 第一次打开时，默认给一级分类添加它的二级分类
  // console.log('data.defaultRegion===', data.array[0]);

  if (data.defaultRegion && data.defaultRegion.length == 4) {
    let region = data.defaultRegion;
    let children = data.cityData;
    for (let j = 0; j < children.length; j++) {
      let condition = children[j].code == region.slice(0, 2);
      if (condition) {
        data.array[1] = data.childArr[j];
        for (let i = 0; i < data.childArr[j].length; i++) {
          let conditionx = data.childArr[j][i].code == region;
          if (conditionx) {
            data.index = [j, i];
          }
        }
        break;
      }
    }
  } else {
    data.array[1] = data.childArr[0];
  }
};
// 获取二级分类
const columnchange = (e: any, index: any) => {
  // 当滚动切换一级分类时，为当前的一级分类添加它的子类
  if (e.detail.column == 0) {
    data.array[1] = data.childArr[e.detail.value];
  }
};
// 选择任务分类
const bindPickerChange = (e: any) => {
  let value = e.detail.value;
  data.index = value;
  let code = '';
  if (data.array[0].length != 0) {
    data.label = data.array[0][data.index[0]].label;
    code = data.array[0][data.index[0]].code;
  }
  if (data.array[1].length != 0) {
    if (data.array[1][data.index[1]].label !== data.label) {
      data.label += data.array[1][data.index[1]].label;
    }
    code = data.array[1][data.index[1]].code;
  }
  emit('getRegion', data.label, code);
  // this.$emit('getRegion', data.name, id);
};
// onLoad(() => {
//   console.log(28383883838388383);

//   getCate();
// });
</script>
